package com.supremex.aisupremex.web.controller;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.supremex.aisupremex.common.mybatis.core.page.PageQuery;
import com.supremex.aisupremex.common.mybatis.core.page.TableDataInfo;
import com.supremex.aisupremex.result.Result;
import com.supremex.aisupremex.web.entity.User;
import com.supremex.aisupremex.web.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author zkx
 * @since 2024-06-03
 */
@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {

	@Autowired
	private UserService userService;


	/**
	 * 用户登录
	 * @param loginUser
	 * @return
	 */
	@PostMapping("/login")
	public Result<User> login(@RequestBody User loginUser) {
		log.info("loginUser:{}",loginUser);
		User user = userService.getOne(Wrappers.<User>lambdaQuery()
				.eq(User::getUserName, loginUser.getUserName()));
		if (user == null){
			return Result.failure("用户名或密码错误！");
		}
		log.info("user:{}",user);
		return Result.success(user);
	}

	/**
	 * 分页查询用户列表
	 * @param user
	 * @param pageQuery
	 * @return
	 */
	@GetMapping("/list")
	public Result<TableDataInfo<User>> list(User user, PageQuery pageQuery) {
		log.info("pageQuery:{}",pageQuery);
		TableDataInfo<User> userTableDataInfo = userService.selectPageUserList(user, pageQuery);
		return Result.success(userTableDataInfo);
	}

	/**
	 * 改变用户状态
	 * @param id
	 * @param accountStatus
	 * @return
	 */
	@PutMapping("/{id}/state/{accountStatus}")
	public Result<String> changeStatus(@PathVariable("id")Long id,@PathVariable("accountStatus")Boolean accountStatus) {
		User user = new User();
		user.setId(id);
		user.setAccountStatus(accountStatus);
		userService.updateById(user);
		return Result.success();
	}

	/**
	 * 新增用户
	 * @param user
	 * @return
	 */
	@PostMapping("/add")
	public Result<String> add(@RequestBody User user) {
		userService.save(user);
		return Result.success();
	}

	/**
	 * 获取单个用户信息
	 * @param id
	 * @return
	 */
	@GetMapping("/{id}")
	public Result<User> getInfo(@PathVariable("id")Long id) {
		User user = userService.getById(id);
		return Result.success(user);
	}

	/**
	 * 修改用户信息
	 * @param id
	 * @param user
	 * @return
	 */
	@PutMapping("/{id}")
	public Result<String> update(@PathVariable("id")Long id,@RequestBody User user) {
		user.setId(id);
		userService.updateById(user);
		return Result.success();
	}

	/**
	 * 删除用户
	 * @param id
	 * @return
	 */
	@DeleteMapping("/{id}")
	public Result<String> delete(@PathVariable("id")Long id) {
		userService.removeById(id);
		return Result.success();
	}

}
